package com.locationtracker.plus.ui.dialog

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.locationtracker.plus.R
import com.locationtracker.plus.app.appViewModel
import com.locationtracker.plus.app.eventViewModel
import com.locationtracker.plus.data.model.bean.UserInfo
import me.hgj.jetpackmvvm.ext.util.notNull

class PhoneInputDialog(context: Context) : Dialog(context) {

    private var phoneEdit: EditText? = null
    lateinit var userInfo: UserInfo

    fun updatePhone(phone: String) {
        phoneEdit?.setText(phone)
    }

    init {
        // 拿到Dialog的Window, 修改Window的属性
        val window = window
        window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        window.decorView.setPadding(0, 0, 0, 0)
        // 获取Window的LayoutParams
        setCancelable(true)
        setCanceledOnTouchOutside(true)
        val attributes = window.attributes
        attributes.width = WindowManager.LayoutParams.MATCH_PARENT
        attributes.gravity = Gravity.CENTER
        // 一定要重新设置, 才能生效
        window.attributes = attributes
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        appViewModel.userInfo.value.notNull(
            {
                userInfo = it
            }, {
                ToastUtils.showShort("Login first!")
                dismiss()
                return@onCreate
            }
        )
        //初始化recyclerview
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_phone_input, null)
        phoneEdit = view.findViewById(R.id.phoneEdit)
        view.findViewById<View>(R.id.phoneSubmit).setOnClickListener { _ ->
            if (phoneEdit == null) return@setOnClickListener
            phoneEdit?.text?.toString()?.let {
                if (it.isEmpty()) {
                    ToastUtils.showShort("Enter phone number first!")
                    return@setOnClickListener
                }
                ActivityUtils.startActivity(Intent().apply {
                    action = Intent.ACTION_SENDTO
                    data = Uri.parse("smsto:$it")
                    putExtra("sms_body", "Hi! I use this app to see location of my family and friends! Join me!  http://locationtp2.snpsmar.cn/LocationTrackerPlus/h5/index.html#/?code=${userInfo.code}&phone=${userInfo.phone}")
                })
                dismiss()
            }
        }
        view.findViewById<View>(R.id.phoneChoose).setOnClickListener {
            eventViewModel.chooseContact.value = System.currentTimeMillis()
        }
        setContentView(view)
    }
}
